const { Withdrawal, User } = require('../models');
const sequelize = require('sequelize');
const { Op, fn, col } = require('sequelize');
const dayjs = require('dayjs');

class WithdrawalService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter, page = 1, page_size = 20, sorter = []) {
		const { fullname, phone, user_id } = filter;

		const where = {};
		if (fullname) where['$user.fullname$'] = { [Op.like]: `%${fullname}%` };
		if (phone) where['$user.phone$'] = { [Op.like]: `%${phone}%` };
		if (user_id) where['user_id'] = user_id;

		const { count: total, rows: data } = await Withdrawal.findAndCountAll({
			include: [{
				model: User,
				as: 'user',
				attributes: ['fullname', 'phone'],
				/*
				where: (() => {
					const where = {};
					if (fullname) where['fullname'] = { [Op.like]: `%${fullname}%` };
					if (phone) where['phone'] = { [Op.like]: `%${phone}%` };
					return where;
				})()
				*/
			}],

			where,
			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: sorter.length ? sorter : [
				['id', 'desc']
			]
		});

		return {
			data,
			total
		}
	}

	async info(where) {
		return await Withdrawal.findOne({
			where
		});
	}

	async delete(id) {
		return await Withdrawal.destroy({
			where: {
				id: { [Op.in]: String(id).split(',') }
			}
		});
	}

	async save(params) {
		['create_time', 'update_time', 'delete_time'].forEach((d) => {
			delete params[d];
		});

		const { id } = params;

		if (id) {
			if (params.status > 0) {
				params.status_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
			}

			//如果审核通过，需要扣除用户账户余额
			if (params.status === 1) {
				const { amount, user_id } = await Withdrawal.findOne({ where: { id } });

				const user = await User.findOne({ where: { id: user_id } });
				await user.decrement('balance', { by: amount });
			}

			return await Withdrawal.update(params, {
				where: {
					id
				}
			})
		} else {
			return await Withdrawal.create(params);
		}
	}
}

exports = module.exports = WithdrawalService;
